import React, { useEffect, useState } from 'react'
import { Button, message, Empty, Modal, Form, DatePicker, notification, Tooltip, Space, Typography } from 'antd'
import useGetTableData from '@/hooks/useGetTableData'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useSendColumns } from './columns'
import { ITableAddType as ITableData } from './types'
import CustomTable from '@/components/CustomTable'
import { useNavigate } from 'react-router-dom'
import './index.less'
import { getProductClassConfigById, getProductClassConfigByType, getSpuOptions } from '@/api/goods'
import dayjs from 'dayjs'
import { queryReserveInvoicePurchaseDetail, reserveInvoiceCreate } from '@/api/purchase'
import { IOptionClass } from '@/pages/Goods/Plan'
import './add.less'
import { getRecentSixMonths } from '@/utils/util'
import { onValuesChange } from '@/utils/onValuesChange'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import useGetClassIds from '@/hooks/useGetClassIds'
import { ArrowLeftOutlined, ExclamationCircleOutlined, QuestionCircleOutlined } from '@ant-design/icons'
import PermissionButton from '@/components/PermissionButton'
const Index: React.FC = () => {
  let SpuTimeout: ITimeoutType
  const navigate = useNavigate()
  const [form] = useForm()
  const [FormSend] = useForm()
  const [loading, setloading] = useState<boolean>(false)
  const [isModalShow, setisModalShow] = useState<boolean>(false)
  const [FreeScan, setFreeScan] = useState<0 | 1>(0)
  const [selectedRowKeys, setselectedRowKeys] = useState<React.Key[]>([])
  const [SpuOptions, setSpuOptions] = useState<IOptionItem[]>([])
  const [SkuOptions, setSkuOptions] = useState<IOptionItem[]>([])
  const { SupplierOption, handleSearchSupplier } = useSearchSupplier('supplierId')
  const { classIdOptions, handleClassIdChange, settinyClassIds, tinyClassIds } = useGetClassIds()
  const [tableData, settableData] = useState<ITableData[]>([])
  const [selectedInfos, setselectedInfos] = useState<ITableData[]>([])
  const defaultDateRange = getRecentSixMonths()
  const { tableProps, params, setParams, search, reset } = useGetTableData<ITableData>(
    queryReserveInvoicePurchaseDetail,
    {
      form: form,
      defaultFieldsParams: {
        createTimeStart: defaultDateRange,
      },
      immediatelySend: false,
    },
  )
  useEffect(() => {
    search({
      ...params,
      createTimeStart: dayjs(defaultDateRange[0]).format('YYYY-MM-DD HH:mm:ss'),
      createTimeEnd: dayjs(defaultDateRange[1]).format('YYYY-MM-DD HH:mm:ss'),
    })
  }, [])
  useEffect(() => {
    const tableData =
      tableProps?.dataSource?.map((item) => {
        return {
          ...item,
          scheduleQty: item.orderQty - item.scheduledQty >= 0 ? item.orderQty - item.scheduledQty : 0,
        }
      }) || []
    settableData(tableData)
  }, [tableProps.dataSource])
  const selectRows = (keys: React.Key[], info: ITableData[]) => {
    setselectedRowKeys(keys)
    setselectedInfos(info)
  }
  const handleSearchSpuOptions = (newValue = '') => {
    if (!newValue) return
    if (SpuTimeout) {
      clearTimeout(SpuTimeout)
      SpuTimeout = null
    }
    const getOptions = async () => {
      const res = await getSpuOptions<{
        spuName: string
        spuCode: string
        designCode: string
      }>({ keyword: newValue })
      if (res.code === 200) {
        const data =
          res.data?.map((item) => {
            return {
              label: `${item?.spuCode}｜${item.spuName}${item?.designCode ? '｜' + item?.designCode : ''}`,
              value: item.spuCode,
            }
          }) || []
        setSpuOptions(data)
      }
    }
    SpuTimeout = setTimeout(getOptions, 500)
  }
  const onModalCancel = () => {
    setisModalShow(false)
    FormSend.resetFields()
  }

  const onSendOk = async (scanFreeStatus: 0 | 1) => {
    if (isModalShow) {
      await FormSend.validateFields()
    }
    console.log(selectedInfos, 'selectedInfos')
    const hasModal = selectedInfos.some((item) => item.orderQty - item.scheduledQty < item.scheduleQty)
    if (hasModal) {
      Modal.confirm({
        title: '提示',
        content: '商品预约数量超过下单数量，是否确认预约？',
        okText: '确认',
        cancelText: '取消',
        icon: <ExclamationCircleOutlined />,
        onOk: async () => {
          await sendOkReq(scanFreeStatus)
        },
      })
    } else {
      await sendOkReq(scanFreeStatus)
    }
  }

  const sendOkReq = async (scanFreeStatus: 0 | 1) => {
    const data = FormSend.getFieldsValue() || {}
    const detailDTOList = selectedInfos?.map((item) => {
      return {
        purchaseOrderCode: item.purchaseOrderCode,
        skuCode: item.skuCode,
        spuCode: item.spuCode,
        scheduleQty: item.scheduleQty,
        orderQty: item.orderQty,
      }
    })
    const paramData = {
      scheduleDeliveryTime:
        data?.scheduleDeliveryTime && dayjs(data.scheduleDeliveryTime).format('YYYY-MM-DD HH:mm:ss'),
      detailDTOList: detailDTOList,
    } as any
    if (scanFreeStatus == 1) paramData.scanFreeStatus = scanFreeStatus
    setloading(true)
    const res = await reserveInvoiceCreate(paramData).finally(() => setloading(false))
    if (res.code === 200) {
      message.success('操作成功')
      search(params)
      setselectedRowKeys([])
      setselectedInfos([])
      onModalCancel()
      setFreeScan(0)
    }
    if (res.code === 820000 && res.failInfo) {
      const failInfo = JSON.parse(res.failInfo)?.map((item: string) => {
        return <div key={item}>商品条码：{item}</div>
      })
      notification.open({
        type: 'warning',
        message: res.msg,
        description: failInfo,
      })
    }
  }
  return (
    <PageContainer className="purchase_deliveryadd_page">
      <div style={{ padding: '12px 12px 0 12px' }}>
        <Typography.Link onClick={() => navigate('/purchase/delivery/list')}>
          <ArrowLeftOutlined style={{ marginRight: 4 }} />
          返回列表页
        </Typography.Link>
      </div>
      <SearchForm
        params={params}
        form={form}
        onValuesChange={(changedValues) => onValuesChange(changedValues, ['purchaseCode'], form)}
        searchConfig={[
          { label: '采购订单', name: 'purchaseCode', type: 'Input' },
          { label: '创建时间', name: 'createTimeStart', type: 'RangePicker', config: { showTime: true } },
          {
            name: 'supplierIds',
            label: '供应商',
            type: 'Select',
            option: SupplierOption,
            config: {
              suffixIcon: null,
              showSearch: true,
              optionFilterProp: 'label',
              filterOption: false,
              mode: 'multiple',
              maxTagCount: 'responsive',
              onSearch: handleSearchSupplier,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
            },
          },
          {
            name: 'queryClassIdList',
            label: '款式分类',
            type: 'Cascader',
            option: classIdOptions,
            placeholder: '请选择款式分类',
            config: {
              changeOnSelect: true,
              onChange: handleClassIdChange,
              onClear: () => settinyClassIds([]),
              fieldNames: { label: 'className', value: 'classConfigId', children: 'childrenList' },
            },
          },
          {
            label: 'SPU商品',
            name: 'spuCode',
            type: 'Select',
            option: SpuOptions,
            placeholder: '款式编码/款式名称/助记码',
            config: {
              suffixIcon: null,
              showSearch: true,
              filterOption: false,
              optionFilterProp: 'label',
              onSearch: handleSearchSpuOptions,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
            },
          },
          {
            label: 'SKU商品',
            name: 'skuCodeList',
            placeholder: '商品条码',
            type: 'Select',
            option: SkuOptions,
            config: {
              mode: 'tags',
              maxTagCount: 'responsive',
              notFoundContent: null,
            },
          },
        ]}
        onFinish={(vals: any) => {
          setselectedRowKeys([])
          setselectedInfos([])
          search({
            ...vals,
            queryClassIdList: tinyClassIds.length > 0 ? tinyClassIds : null,
            createTimeStart: vals?.createTimeStart?.[0] && dayjs(vals.createTimeStart[0]).format('YYYY-MM-DD HH:mm:ss'),
            createTimeEnd: vals?.createTimeStart?.[1] && dayjs(vals.createTimeStart[1]).format('YYYY-MM-DD HH:mm:ss'),
          })
        }}
        onReset={() => {
          setselectedRowKeys([])
          setselectedInfos([])
          reset()
        }}
        initialValues={{ queryClassIdList: [] }}
        extra={
          <div className="table_extra_flex">
            <Button
              loading={loading}
              onClick={async () => {
                if (selectedRowKeys.length === 0) {
                  message.warning('请勾选需要操作的列表数据！')
                  return
                }
                const firstInfo = selectedInfos?.[0]
                const hasEdit = selectedInfos.every((item) => item.scheduleQty)
                if (!hasEdit) {
                  message.warning('请输入本次预约数量！')
                  return
                }
                const isCommon = selectedInfos.every((item) => item.purchaseOrderCode == firstInfo.purchaseOrderCode)
                if (!isCommon) {
                  message.warning('请选择同一笔采购订单下的明细！')
                  return
                }
                //供应商有需要扫码装箱的配置时，无需弹窗填写预约发货时间！
                const allNeedScan = selectedInfos.every((item) => item.supplierScanStatus == 0)
                if (allNeedScan) {
                  onSendOk(0)
                } else {
                  setisModalShow(true)
                  setFreeScan(0)
                }
              }}
            >
              提交预约发货单
            </Button>
            <PermissionButton
              loading={loading}
              iconPosition="end"
              permission="addDeliveryNoScan"
              onClick={async () => {
                if (selectedRowKeys.length === 0) {
                  message.warning('请勾选需要操作的列表数据！')
                  return
                }
                const firstInfo = selectedInfos?.[0]
                const hasEdit = selectedInfos.every((item) => item.scheduleQty)
                if (!hasEdit) {
                  message.warning('请输入本次预约数量！')
                  return
                }
                const isCommon = selectedInfos.every((item) => item.purchaseOrderCode == firstInfo.purchaseOrderCode)
                if (!isCommon) {
                  message.warning('请选择同一笔采购订单下的明细！')
                  return
                }
                setisModalShow(true)
                setFreeScan(1)
              }}
            >
              <Tooltip title="该功能适用于仓库多到货补单的场景，提交的预约发货单无须扫码装箱" placement="top">
                <span>提交预约发货单（免扫码）</span>
                <QuestionCircleOutlined />
              </Tooltip>
            </PermissionButton>
          </div>
        }
      ></SearchForm>
      <CustomTable
        bordered
        isSelection
        selectRows={selectRows}
        selectedRowKeys={selectedRowKeys}
        columns={useSendColumns({ tableData, settableData, selectedRowKeys })}
        {...tableProps}
        dataSource={tableData}
        rowKey={(rows) => rows.id}
        isScrollY
        extraHeight={30}
      />
      <Modal
        title="预约发货"
        open={isModalShow}
        onCancel={onModalCancel}
        footer={
          <Space>
            <Button onClick={onModalCancel}>取消</Button>
            <Button type="primary" onClick={() => onSendOk(FreeScan)} loading={loading}>
              确定
            </Button>
          </Space>
        }
      >
        <Form form={FormSend} layout="vertical">
          <Form.Item
            label="预约发货时间"
            name="scheduleDeliveryTime"
            style={{ marginBottom: 0 }}
            rules={[
              {
                required: true,
                message: '请选择预约发货时间',
              },
            ]}
          >
            <DatePicker showTime></DatePicker>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  )
}

export default Index
